﻿/**
 * Created by songj on 2015/12/11.
 */
define(['angular',
    'framework/msg/GillionMsgModule',
    'framework/dataGrid/DataGridModule',
    'framework/pagination/GillionPaginationModule',
    'framework/datasource/DataSourceModule',
    'framework/dropdown/GillionDropdownModule',
    'framework/date/DateModule',
    'angular-underscore',
    'angular-ui-tree',
    'bootstrap'
], function (angular) {
    var module = angular.module('ValidatorModule',
        ['GillionMsgModule', 'DataGridModule', 'GillionPaginationModule',
            'DataSourceModule', 'DateModule', 'GillionDropdownModule','ui.tree'])
        .controller('ValidatorController', ['$scope', 'GillionMsgService', '$dataSourceManager', '$timeout', 'Arrays', "$location",'Resource','GillionMsg','$compile','$http',
                function ($scope, GillionMsgService, $dataSourceManager, $timeout, Arrays, $location,Resource,GillionMsg) {
                    $scope.validatorConfig = GillionMsgService.getInputData();
                    var validatorConfigResource = Resource("/grule-manager/validator");
                    var initView = function () {
                        $scope.data = transformToTree($scope.validatorConfig.validator || "{}");

                        $timeout(function(){
                            if (!$scope.validatorConfig.validator){
                                $("#validatorAddNode").trigger("click");
                            }
                        });
                    };
                    var transformToTree = function(validatorConfigStr){
                        var validatorConfig =eval('('+ validatorConfigStr+')');
                        var nodes = [];
                        for (var key in validatorConfig){
                            var node = {
                                "nodeName":key
                            };
                            if (validatorConfig[key].elem){
                                node.nodes = transformToTree(validatorConfig[key].elem);
                            } else {
                                node.configs = validatorConfig[key];
                            }
                            nodes.push(node);
                        }
                        return nodes;
                    };



                    $scope.addNode = function(node){
                        var childNode = {'nodeName':''};
                        if (angular.isArray(node)) {
                            node.push(childNode);
                        } else if (!node.nodes) {
                            node.nodes = [childNode];
                        } else {
                            node.nodes.push(childNode);
                        }
                        node.configs=null;
                    };
                    $scope.collapseAll = function () {
                        $scope.$broadcast('angular-ui-tree:collapse-all');
                    };

                    $scope.expandAll = function () {
                        $scope.$broadcast('angular-ui-tree:expand-all');
                    };

                    $scope.toggle = function (scope) {
                        if (scope) {
                            scope.toggle();
                        }
                    };
                    var transTreeToForm = function (nodes) {
                        var i, node,
                            validatorConfig = {};
                        for (i=0;i<nodes.length;i++) {
                            node = nodes[i];
                            if (node['nodes'] && node['nodes'].length>0){
                                if (!validatorConfig[node['nodeName']]) validatorConfig[node['nodeName']] = {};
                                validatorConfig[node['nodeName']]['elem'] = transTreeToForm(node['nodes']);
                            } else {
                                validatorConfig[node['nodeName']] = node['configs'] || {};
                            }

                        }
                        return validatorConfig;
                    };
                    $scope.selectNode = function(node,event){
                        var ele =  $(event.target);
                        if(ele.attr("role")==="functionArea"
                            || ele.closest('.tree-node-edit-content').length==1 || (node.nodes && node.nodes.length>0)){
                            return;
                        }

                        $(".tree-node-select").removeClass("tree-node-select");
                        if ($scope.currentSelectNode == node){
                            $scope.currentSelectNode = null;
                            ele.closest(".tree-node").removeClass("tree-node-select");
                        } else{
                            ele.closest(".tree-node").addClass("tree-node-select");
                            $scope.currentSelectNode = node;
                            validCheckBoxView(node);
                        }
                    };

                    var validCheckBoxView = function(node) {
                        var configs = node.configs;
                        if (!configs) {
                            $scope.validPattern = false;
                            $scope.validNotEmpty = false;
                            $scope.validLength = false;
                            $scope.validRange = false;
                            $scope.validRequire = false;
                            return;
                        }
                        var validPatternSetting = configs['pattern'],
                            validNotEmptySetting = configs['notEmpty'],
                            validLengthSetting = configs['length'],
                            validRangeSetting = configs['range'],
                            validRequireSetting = configs['require'];
                        $scope.validPattern = validPatternSetting!==undefined;
                        $scope.validNotEmpty = validNotEmptySetting!==undefined;
                        $scope.validLength = validLengthSetting!==undefined;
                        $scope.validRange = validRangeSetting!==undefined;
                        $scope.validRequire = validRequireSetting!==undefined;

                        $scope.validPatternSetting = validPatternSetting;
                        $scope.validNotEmptySetting = validNotEmptySetting;
                        $scope.validLengthSetting = validLengthSetting;
                        $scope.validRangeSetting = validRangeSetting;
                        $scope.validRequireSetting = validRequireSetting;
                    };
                    $scope.deleteNode = function (node) {
                        if (node){
                            node.remove();
                            console.log($scope.data);
                        }
                    };

                    $scope.save = function () {
                        $scope.validatorConfig.settings = transTreeToForm($scope.data);
                        $scope.validatorConfig.validator = JSON.stringify($scope.validatorConfig.settings);
                        if ($scope.validatorConfig.id) {
                            validatorConfigResource.update($scope.validatorConfig, function (response) {
                                if (response.success) {
                                    GillionMsgService.close();
                                }
                            })
                        } else {//新增validator
                            $scope.validatorConfig.projectId = $scope.validatorConfig.projectId;
                            validatorConfigResource.save($scope.validatorConfig, function (response) {
                                if (response.success) {
                                    GillionMsgService.close();
                                }
                            })
                        }
                    }

                    $scope.validPatternCheck = function (selected) {
                        if (selected) {
                            if (!$scope.currentSelectNode.configs) {
                                $scope.currentSelectNode.configs = {};
                            }
                            $scope.validPatternSetting = $scope.currentSelectNode.configs['pattern'] = {};
                        } else {
                            delete $scope.currentSelectNode.configs['pattern'];
                        }
                    };

                    $scope.validNotEmptyCheck = function (selected) {
                        if (selected) {
                            if (!$scope.currentSelectNode.configs) {
                                $scope.currentSelectNode.configs = {};
                            }
                            $scope.validNotEmptySetting = $scope.currentSelectNode.configs['notEmpty'] = {};
                        } else {
                            delete $scope.currentSelectNode.configs['notEmpty'];
                        }
                    };
                    $scope.validLengthCheck = function (selected) {
                        if (selected) {
                            if (!$scope.currentSelectNode.configs) {
                                $scope.currentSelectNode.configs = {};
                            }
                            $scope.validLengthSetting = $scope.currentSelectNode.configs['length'] = {};
                        } else {
                            delete $scope.currentSelectNode.configs['length'];
                        }
                    };
                    $scope.validRangeCheck = function (selected) {
                        if (selected) {
                            if (!$scope.currentSelectNode.configs) {
                                $scope.currentSelectNode.configs = {};
                            }
                            $scope.validRangeSetting = $scope.currentSelectNode.configs['range'] = {};
                        } else {
                            delete $scope.currentSelectNode.configs['range'];
                        }
                    };
                    $scope.validRequireCheck = function (selected) {
                        if (selected) {
                            if (!$scope.currentSelectNode.configs) {
                                $scope.currentSelectNode.configs = {};
                            }
                            $scope.validRequireSetting = $scope.currentSelectNode.configs['require'] = {};
                        } else {
                            delete $scope.currentSelectNode.configs['require'];
                        }
                    };

                    initView();
                }
            ]
        );

    module.config(['$locationProvider', function($locationProvider) {
        $locationProvider.html5Mode(true);
    }]);
    return module;
});
